const getWhere = (where) => {
  let whereStr = ''
  const whereItem = (state, key, type, val) => {
    if (type === 'in') {
      console.log(val);
      return `${state} ${key} in(${val.join(',')}) `
    } else if (type === 'like') {
      return `${state} ${key} like "%${val}%" `
    } else if (type === 'range') {
      // return `${state} ${key} >= "${val[0]}" and ${key} <= "${val[1]}"`
      return `${state} ${key} between "${val[0]}" and "${val[1]}"`
    }
    return `${state} ${key} ${type} "${val}" `
  }
  Object.entries(where).forEach(whereData => {
    const [key, data] = whereData
    if (!whereStr) {
      whereStr += whereItem('where', key, data.type, data.val)
    } else {
      whereStr += whereItem('and', key, data.type, data.val)
    }
  })
  return whereStr
}
const getOrder = (orders) => {
  let ordersStr = ''
  orders.forEach(item => {
    if (!ordersStr) {
      ordersStr += `order by ${item[0]} ${item[1]}`
    } else {
      ordersStr += `, ${item[0]} ${item[1]}`
    }
  })
  return ordersStr
}

const getSqlCount = (name, option) => {
  const { where } = option
  const sql = `select count(1) from ${name} `
  const whereStr = getWhere(where)

  return sql + whereStr
}

const getSqlSelect = (name, option) => {
  const { where, orders, limit, offset } = option
  const sql = `select * from ${name} `
  const whereStr = getWhere(where)
  const ordersStr = getOrder(orders)
  let limitStr = ''

  if (limit && offset) {
    limitStr = ` limit ${(offset - 1) * limit}, ${(offset - 1) * limit + limit}`
  }
  return sql + whereStr + ordersStr + limitStr
}

module.exports = {
  getSqlCount,
  getSqlSelect
}